import React, { Component } from "react";
import { connect } from 'react-redux'
import AdvancedTable from "components/advanced-table";
import financialService from "../financialService";
import { deepFullCopy, messages } from "share/common";
import Control from 'components/control'
import Selector from 'components/selector'
import { Button, Alert, Modal, Select, message } from 'antd'
import moment from "moment";
import WarpBillItem from './warp-bill-item'
import WarpAccountCode from "./warp-account-code";
import menuRoute from "routes/menuRoute";
import SlideFrame from "components/slide-frame";
import refundContent from "../../loan-billing/template/refund-content";
import AsyncExport from "components/template/async-export/async-export";
import Space from 'components/space'
import Department from "components/template/department";
const { Option } = Select;

@connect(mapStateToProps)
class NewEntryDetail extends Component{

  handleChangeSetOfBook = (value, isTitle) => {
    const { searchForm } = this.state;
    let setOfBooksId = searchForm.find(item => item.id === 'functionDefineId').props.listExtraParams.setOfBooksId;
    if (setOfBooksId !== value.id) {
      if (!isTitle) {
        this.advancedTableRef.advancedSearchRef.props.form.setFieldsValue({
          accountCode: undefined,
          functionDefineId: undefined,
          periodSetList: undefined,
          companyId: undefined,
          currencyCode: undefined
        });
      }
      searchForm.map(item => {
        if (item.id === 'accountCode') {
          item.component.props = { setOfBooksId: value.id };
        }
        if (item.id === 'functionDefineId' || item.id === 'periodSetList') {
          item.props.listExtraParams = { setOfBooksId: value.id };
        }
        if (item.id === 'companyId') {
          item.props.extraParams = { enabled: true, setOfBooksId: value.id }
        }
        if (item.id === 'currencyCode') {
          item.props.params = { userOId: this.props.loginUser.userOID, setOfBooksId: value.id }
        }
      });
      this.setState({ searchForm });
    }
  };

  options = [
    { label: messages('finance-2.key19')/*未导入*/, value: '1001' },
    { label: messages('finance-2.key20')/*导入中*/, value: '1002' },
    { label: messages('finance-2.key21')/*已导入*/, value: '1003' },
    { label: messages('finance-2.key22')/*导入失败*/, value: '1004' }
  ];

  state = {
    modalVisible: false,
    batchBtnLoading: false,
    batchSize: 999,
    searchForm: [
      {
        component: isTitle => <Selector
          allowClear={false}
          type={'setOfBooksByTenant'}
          params={{ roleType: 'TENANT' }}
          entity
          onChange={value => this.handleChangeSetOfBook(value, isTitle)}
        />,
        id: 'setOfBooksId',
        judgeInTitle: true,
        label: messages('finance-2.key16')/*账套*/,
        initialValue: {
          setOfBooksName: this.props.company.setOfBooksName,
          id: this.props.company.setOfBooksId
        },
        tagUnclosed: true,
        parser: value => ({ setOfBooksId : value ? value.id : undefined }),
        tagParser: value => value.setOfBooksName
      },
      {
        id: 'companyId', label: messages('finance-2.key23')/*公司*/, component: 'Chooser',
        props: {
          type: 'available_company_setOfBooks',
          labelKey: 'name',
          valueKey: 'id',
          single: true,
          extraParams:{ enabled: true, setOfBooksId: this.props.company.setOfBooksId }
        },
        parser: value => ({ companyId: value && value[0] ? value[0].id : undefined }),
        tagParser: value => (value.map(item => item.name).join(','))
      },
      {
        id: 'departmentId', label: messages('common.department')/*部门*/, component: <Department single/>,
        parser: value => ({ departmentId: value ? value[0].id : undefined }),
        tagParser: value => (value.map(item => item.title).join(','))
      }, WarpBillItem,
      {
        id: 'functionDefineId', label: messages('finance-2.key24')/*核算业务类型*/, component: 'Chooser',
        props: {
          labelKey: 'typeName',
          valueKey: 'id',
          type: 'choose_function_define',
          listExtraParams: { setOfBooksId: this.props.company.setOfBooksId },
          single: true
        },
        parser: value => ({ functionDefineId: value ? value[0].id : undefined }),
        tagParser: value => value.map(item => item.typeName).join(',')
      },
      {
        id: 'periodSetList', label: messages('finance-2.key25')/*凭证期间*/, component: 'Chooser',
        props: {
          labelKey: 'periodName',
          valueKey: 'periodName',
          type: 'period_set',
          listExtraParams: { setOfBooksId: this.props.company.setOfBooksId }
        },
        parser: value => ({ periodSetList: value ? value.map(item => item.periodName) : undefined }),
        tagParser: value => value.map(item => item.periodName).join(',')
      },
      {
        id: 'transactionDate', label: messages('finance-2.key26')/*事务日期*/, component: 'DateRangePicker',
        parser: value => ({
          transactionDateStart: value && value[0] ? moment(value[0].format('YYYY-MM-DD 00:00:00')).utc() : undefined,
          transactionDateTo: value && value[1] ? moment(value[1].format('YYYY-MM-DD 23:59:59')).utc() : undefined
        }),
        initialValue: [moment().subtract(1, 'month'), moment()],
      },
      {
        id: 'accountCode', label: messages('finance-2.key27')/*科目代码*/, component: <WarpAccountCode setOfBooksId={this.props.company.setOfBooksId}/>,
        parser: value => ({
          accountCodeFrom: value && value.accountCodeFrom ? value.accountCodeFrom[0].accountCode : undefined,
          accountCodeTo: value && value.accountCodeTo ? value.accountCodeTo[0].accountCode : undefined
        }),
        tagParser: value => `${value.accountCodeFrom ? value.accountCodeFrom.map(item => item.accountCode).join(',') : ''}${value.accountCodeTo ? '-' + value.accountCodeTo.map(item => item.accountCode).join(',') : ''}`
      },
      {
        id: 'currencyCode', label: messages('common.currency')/*币种*/, component: 'Selector',
        props: {
          type: 'currency',
          params: { userOId: this.props.loginUser.userOID, setOfBooksId: this.props.company.setOfBooksId },
          filter: item => item.enable,
          searchIfKeywordIsNull: true
        },
        dataIndex: 'currencyCode'
      },
      {
        id: 'documentCode', label: messages('finance-2.key28')/*凭证编号*/, component: 'Input'
      },
      {
        id: 'importFlag', label: messages('finance-2.key29')/*导入标志*/, component: <Select style={{ width: '100%' }}>
          {this.options.map(item => <Option key={item.value}>{item.label}</Option>)}
        </Select>,
        parser: value => ({ importFlag: value ? Number(value) : undefined }),
        initialValue: '1001',
        tagParser: value => this.options.find(item => item.value === value).label
      },
      {
        id: 'importDate', label: messages('finance-2.key30')/*导入日期*/, component: 'DateRangePicker',
        parser: value => ({
          importDateFrom: value && value[0] ? moment(value[0].format('YYYY-MM-DD 00:00:00')).utc() : undefined,
          importDateTo: value && value[1] ? moment(value[1].format('YYYY-MM-DD 23:59:59')).utc() : undefined
        })
      },
      {
        id: 'remark', label: messages('finance-2.key31')/*摘要*/, Component: 'Input'
      }
    ],
    searchParams: {}
  };

  service = (page, size, searchParams) => {
    const { loginUser } = this.props;
    this.setState({ searchParams });
    return financialService.getEntryList(Object.assign(searchParams, {
      page,
      size,
      tenantId: loginUser.tenantId,
      operatorId: loginUser.id
    }))
  };

  columns = [
    { title: messages('finance-2.key16')/*账套*/, dataIndex: 'setOfBooksName' },
    { title: messages('finance-2.key28')/*凭证编号*/, dataIndex: 'documentCode' },
    { title: messages('finance-2.key24')/*核算业务类型*/, dataIndex: 'functionDefineCode' },
    {
      title: messages('finance-2.key32')/*单据编号*/, dataIndex: 'businessCode',
      render: (value, record) => <a onClick={e => this.handleToBill(e, record)}>{value}</a>
    },
    { title: messages('finance-2.key23')/*公司*/, dataIndex: 'companyName' },
    {
      title: messages('finance-2.key26')/*事务日期*/,
      dataIndex: 'transactionDate',
      render: value => moment(value).format('YYYY-MM-DD HH:mm:ss')
    },
    { title: messages('finance-2.key25')/*凭证期间*/, dataIndex: 'periodSet' },
    { title: messages('common.currency')/*币种*/, dataIndex: 'currencyCode' },
    { title: messages('finance-2.key31')/*摘要*/, dataIndex: 'remark' },
    {
      title: messages('finance-2.key33')/*会计科目*/,
      dataIndex: 'accountCode',
      render: (value, record) => record.accountName ? `${value}-${record.accountName}` : value
    },
    { title: messages('finance-2.key34')/*借方原币金额*/, dataIndex: 'debitAmount' },
    { title: messages('finance-2.key35')/*贷方原币金额*/, dataIndex: 'creditAmount' },
    { title: messages('finance-2.key36')/*借方本币金额*/, dataIndex: 'debitBaseAmount' },
    { title: messages('finance-2.key37')/*贷方本币金额*/, dataIndex: 'creditBaseAmount' },
    {
      title: messages('finance-2.key29')/*导入标志*/, dataIndex: 'importFlag',
      render: value => this.options.find(item => Number(item.value) === value).label
    },
    {
      title: messages('finance-2.key30')/*导入日期*/,
      dataIndex: 'importDate',
      render: value => value ? moment(value).format('YYYY-MM-DD HH:mm:ss') : '-'
    }
  ];

  handleToBill = (e, record) => {
    e.stopPropagation();
    if (record.entityType === 1002) {
      window.open(
        menuRoute.getRouteItem('expense-report-detail-entry', 'key').url
          .replace(':expenseReportOID', record.entityOid)
          .replace(':pageFrom', 'entry')
      );
    } else if (record.entityType === 3001) {
      window.open(
        menuRoute.getRouteItem('loan-detail-entry', 'key').url
          .replace(':loanBillOID', record.entityOid)
          .replace(':formOID', record.formOID)
      );
    } else if (record.entityType === 7001) {
      window.open(
        menuRoute.getRouteItem('payment-details-entry', 'key').url
          .replace(':paymentRequestOID', record.entityOid)
      );
    } else {
      SlideFrame.open({
        content: refundContent,
        params: {
          refundParams: record.entityOid,
          pathname: ''
        },
        title: messages('finance-2.key38')/*还款详情*/,
      }, this);
    }
  };

  toGenerateExpenseBatch = () => {
    const { loginUser, company, makeBatchDone } = this.props;
    this.setState({ batchBtnLoading: true });
    let params = deepFullCopy(this.advancedTableRef.state.searchParams);
    params.batchLimit = this.state.batchSize;
    params.tenantId = loginUser.tenantId;
    params.operatorOid = loginUser.userOID;
    params.operatorEmployeeId = loginUser.employeeID;
    params.operatorName = loginUser.fullName;
    params.setOfBooksName = company.setOfBooksName;
    params.operatorId = loginUser.id;
    financialService.makeBatch(params).then(() => {
      message.success(messages('finance-2.key39')/*批次生成成功*/);
      this.setState({ batchBtnLoading: false, modalVisible: false },() => {
        makeBatchDone();
      });
      this.getList()
    }).catch(e => {
      this.setState({ batchBtnLoading: false, modalVisible: false });
      message.error(e.response.data.message);
    })
  };

  render() {
    const { modalVisible, batchBtnLoading, batchSize, searchForm, searchParams } = this.state;
    const { loginUser, language } = this.props;
    let noticeMessage = messages('finance-2.key40')/*生成批次后，分录的<span class='color-blue'>导入标志</span>将会变为已导入，列表中未导入的分录可生成批次。*/;
    return (
      <Control>
        <div style={{ height: '100%' }}>
          <AdvancedTable
            service={this.service}
            title={messages('finance-2.key1')/*分录信息*/}
            rowKey={'id'}
            tableName='entry-detail'
            columns={this.columns}
            onRef={ref => this.advancedTableRef = ref}
            searchForm={searchForm}
            footer={<Space>
              <Button
                data-control={'entry-information.hidden'}
                onClick={() => this.setState({ modalVisible: true })}
              >
                {messages('finance-2.key41')/*生成批次*/}
              </Button>
              <AsyncExport
                title={messages('finance-2.key42')/*导出数据*/}
                style={{ display: 'inline-block' }}
                params={{
                  tenantId: loginUser.tenantId,
                  setOfBooksId: searchParams.setOfBooksId,
                  operatorOid: loginUser.userOID,
                  implName: 'journalLineDownloadServiceImpl',
                  isAsync: true,
                  otherDownloadMsg: searchParams,
                  language: language.code
                }}
              />
            </Space>}
            header={(
              <Alert
                type="info" showIcon
                message={<div dangerouslySetInnerHTML={{__html: noticeMessage}}/>}
              />
            )}
          />
          <div className="modal-container"/>
          <Modal
            visible={modalVisible}
            title={messages('finance-2.key41')/*生成批次*/}
            getContainer={() => document.getElementsByClassName('modal-container')[0]}
            footer={[
              <Button key="cancel"
                      onClick={() => this.setState({ modalVisible: false })}>
                {messages('common.cancel')/*取消*/}
              </Button>,
              <Button key="ok"
                      type="primary"
                      loading={batchBtnLoading}
                      onClick={this.toGenerateExpenseBatch}>
                {messages('common.ok')/*确定*/}
              </Button>,
            ]}
            onCancel={() => this.setState({ modalVisible: false })}
          >
            <Alert
              type="info" showIcon
              message={messages('finance-2.key43')/*当批次中数量过大，可能导致下游导入失败，请根据您的财务系统进行选择。推荐：999条分录/批*/}
            />
            <div style={{marginTop: '10px'}}> {messages('finance-2.key44')/*设置打印批次*/} :
              <Select value={batchSize} onChange={value => this.setState({ batchSize: value })}>
                <Option value={999}>999</Option>
                <Option value={9999}>9999</Option>
                <Option value={99999}>99999</Option>
              </Select>
              / {messages('finance-2.key45')/*批*/}
            </div>
          </Modal>
        </div>
      </Control>
    )
  }

}

function mapStateToProps(state){
  return {
    company: state.login.company,
    loginUser: state.login.loginUser,
    language: state.main.language
  }
}

export default NewEntryDetail
